﻿using Able.Web.filter;
using Api.BLL;
using Api.Model;
using Api.Web.filter;
using Api.Web.helper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Api.Web.Controllers
{
    [NoCheckProjectAttribute]
    [NoNeedLogin]
    public class AccountController : BaseController
    {
        public ActionResult Login(string returnUrl)
        {
            if (Th.IsLogin)
            {
                if (!string.IsNullOrEmpty(returnUrl))
                {
                    //這裡注意一個坑 response.redirect("http://www.baidu.com")這種絕對地址redirect是沒有問題的,但是我傳入的returnurl參數是使用urlencode編碼過的,所以必須解碼,否則redirect中無法匹配到http://就會以為是普通字符串直接拼接了
                    Response.Redirect(Server.UrlDecode(returnUrl));
                    return View();
                }
                return Redirect("~/");
            }
            return View();
        }

        [HttpPost]
        public ActionResult Login([Bind(Include = "LoginName,LoginPwd")]User user, string returnUrl)
        {
            if (ModelState.IsValid && user != null)
            {
                var model = UserBLL.Current.GetModel(s => s.LoginName == user.LoginName);
                if (model == null)
                {
                    ModelState.AddModelError("LoginError", "用戶不存在");
                    return View();
                }

                if (model.LoginPwd == user.LoginPwd)
                {
                    CookieHelper.SetLoginCookie(model);
                    if (!string.IsNullOrEmpty(returnUrl))
                    {
                        return Redirect(Server.UrlDecode(returnUrl));
                    }
                    return Redirect("~/");
                }
                else
                {
                    ModelState.AddModelError("LoginError", "秘密錯誤");
                }
            }
            else
            {
                ModelState.AddModelError("LoginError", "參數錯誤");
            }
            return View();
        }

        public ActionResult LogOut()
        {
            CookieHelper.RemoveLoginCookie();
            return RedirectToAction("Login", "Account");
        }
    }
}